c++ - 在 C++ 中,如果我通过引用将 CString 传递给函数并将其分配给另一个 CString,它将被截断

标签 c++ pass-by-reference truncate cstring

一些简单的代码在我一直使用的 sdk 中开始出现故障,而且它显然已经正常工作了很长时间,事实上我几乎可以肯定我已经编译了部分代码并且他们有工作,但最近失败了。

在调试器中确认值的示例:

void SomeFunction(CString& paramstring) //let's pretend we pass a string with the value "hello"
{
     int size=paramstring.GetLength(); //size now contains an incorrect shorter value like 4
     CString localstring=paramstring;//localstring contains something like "hell" or "hel"
}

为什么会发生这种情况的任何想法

最佳答案

我在控制台应用程序中尝试了您的代码,它运行良好问题来自您代码的另一部分,这里是代码尝试(使用 MFC)

#include <iostream>
#include <afx.h>
using namespace std;

//let's pretend we pass a string with the value "hello"
void fun(CString& paramstring)
{
    int size=paramstring.GetLength();  
    cout<<"size= "<<size<<"\n";
    CString localstring=paramstring;
    wcout<<"string = "<<(LPCTSTR)localstring<<"\n";
}

int main()
{
    CString s ("Hello");
    fun(s);
}

输出:

size = 5 string = Hello

关于c++ - 在 C++ 中,如果我通过引用将 CString 传递给函数并将其分配给另一个 CString,它将被截断,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8087566/

相关文章:

c++ - 从文件 C++ 中读取(逐行 - 混合变量)

c++ - 这个 const 引用是否保留了它的生命?

R 中的函数,传递数据框和列名

html - 截断 html 表内字符串的另一端

c++ - 枚举二进制序列

c++ - 按引用调用和按值调用之间的区别

c++ - 为什么这段代码使用不同的参数传递策略没有显着的性能差异?

c++类只能通过引用传递

ruby - 我如何...截断数组中的字符串

.net - 截断小数不四舍五入