有关declspec属性的问题 [英] A question about declspec property
问题描述
我的课堂上有这样的定义
I have a definition like this in my class
public:
__declspec(property(get = getName, put = putName)) wstring Name;
wstring getName() {return m_sName;}
void putName(wstring Value) {m_sName = Value;}
private:
wstring m_sName;
但是当我这样做时,它不会获得正确的指针
but when I do this, it would not get the correct pointer
TCHAR* tcharStr = const_cast<TCHAR*>(m_vecMFC[nMfcIndex]->Name.c_str());
假设这些是一个字符串,例如在m_sName的内存中:
41 00 72 00 32 00 20 00 32 00 32 00 00 00
但是当我读取tcharStr的内存时,它变为:
00 00 72 00 32 00 20 00 32 00 32 00 00 00
因此,它成为NULL字符串.
但为什么?有人可以给我一些想法吗?
谢谢!
Suppose these is a string like in the memory of m_sName:
41 00 72 00 32 00 20 00 32 00 32 00 00 00
but when I read memory of tcharStr, it becomes:
00 00 72 00 32 00 20 00 32 00 32 00 00 00
So, it becomes a NULL string.
But Why? Can anybody give me some idea??
Thanks!
推荐答案
存储从c_str()调用中获得的指针不是一个好主意.使用_tcscpy复制字符串是一个更好的主意.
至于失败的原因-因为方法是这样声明的:
It''s not a good idea to store the pointers you get from c_str() calls. It is a much better idea to make a copy of the string using _tcscpy.
As to why it fails - because the method is declared like this:
wstring getName()
调用它时得到的是m_sName的副本-很快就会消失.这就是为什么您从c_str()获得的指针不再有效,并且可能发生奇怪的事情的原因(它甚至可能在释放中起作用一段时间,然后突然失效).如果需要实际的m_sName,则需要定义如下函数:
What you get when you call it is a copy of m_sName - which than disappears pretty quickly. And that''s why the pointer you get from c_str() is no longer valid and strange things may happen (it may even work in release for a while and than fail out of the blue). If you want the actual m_sName you would need to define the function like this:
wstring& getName()
您甚至可以在代码中同时拥有两个函数,然后比较c_str()返回的指针-看到区别了吗?
但是正如我在本文开头所说的那样-使用c_str()返回的指针不是一个好主意.始终复制一份更安全,更好的程序:)
祝你好运!
You can even have both functions in your code and than compare the pointers c_str() returns - see the difference?
But as I said at the start of this post - it is NOT a good idea to use the c_str() returned pointer. Always, always make a copy for a safer and better working programs :)
Best of luck!!
这篇关于有关declspec属性的问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!