C++访问类内的浮点指针 ->访问冲突
Visual C++,Microsoft Visual Studio 2010 Express:
从这个 malloc 访问可以工作:
float* block = (float *)_aligned_malloc(32 * sizeof(float), CACHE_ALIGNMENT);
block[0] = (float)30; // I work fine.
但是当它在这个类中时,它不起作用:
class Test
{
private:
//static const int numberOfElements = 1024;
public:
float* block1;
float* block2;
// Constructor
Test::Test(int nElements)
{
float* block1 = (float *)_aligned_malloc(nElements * sizeof(float), CACHE_ALIGNMENT);
float* block2 = (float *)_aligned_malloc(nElements * sizeof(float), CACHE_ALIGNMENT);
}
// Destructor
Test::~Test(void)
{
_aligned_free(block1);
_aligned_free(block2);
}
};
...
Test testClass = Test(32);
testClass.block1[0] = (float)30; // Access violation!
...
或者如果声明为指针,则相同的事情(这是我第一次尝试的方式):
Test* testClass = new Test(32);
testClass.block1[0] = (float)30; // Access violation!
什么是当 float* 在类中定义时,我在访问值方面做错了?问题是别的吗?
Visual C++, Microsoft Visual Studio 2010 Express:
Access from this malloc works:
float* block = (float *)_aligned_malloc(32 * sizeof(float), CACHE_ALIGNMENT);
block[0] = (float)30; // I work fine.
But when it is inside this class, it does not work:
class Test
{
private:
//static const int numberOfElements = 1024;
public:
float* block1;
float* block2;
// Constructor
Test::Test(int nElements)
{
float* block1 = (float *)_aligned_malloc(nElements * sizeof(float), CACHE_ALIGNMENT);
float* block2 = (float *)_aligned_malloc(nElements * sizeof(float), CACHE_ALIGNMENT);
}
// Destructor
Test::~Test(void)
{
_aligned_free(block1);
_aligned_free(block2);
}
};
...
Test testClass = Test(32);
testClass.block1[0] = (float)30; // Access violation!
...
Or if declared as a pointer, the same thing (this is how I first tried it):
Test* testClass = new Test(32);
testClass.block1[0] = (float)30; // Access violation!
What am I doing wrong in terms of accessing the values when the float* is define inside a class? Is the problem something else?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您分配给构造函数的局部变量,而不是成员变量。尝试类似的操作
并检查值以确保分配成功。
You assign to the variables local to constructor, not member variables. Try something like
and check the values to make sure allocation succeeded.
构造函数局部变量
block1
和block2
的声明隐藏了成员变量block1
和block2
。使用
g++
,您可以使用-Wshadow
选项获得警告。对于 Visual Studio,恐怕没有选项可以在变量遮蔽另一个变量时发出警告。The declarations of the variables
block1
andblock2
local to the constructor shadow the member variablesblock1
andblock2
.With
g++
you can get a warning for this with-Wshadow
option. With Visual Studio I'm afraid there is no option to warn when a variable shadows another one.