hp ux - C++ std::string Constructor

hp ux - C++ std::string Constructor

本文关键字:string Constructor std C++ ux hp      更新时间:2023-10-16
对此

的任何想法将不胜感激:

std::string s1 = "hello";
std::string s2 = std::string(s1);

我现在希望这两个字符串是独立的,即我可以将", world"附加到 s2 中,s1 仍然会读作"hello"。这是我在 Windows 和 Linux 上找到的,但在HP_UX机器上运行代码似乎 s2 和 s1 是同一个字符串,因此修改 s2 会更改 s1。

这听起来绝对疯狂吗,有人见过类似的东西吗?

虽然我无法重现OP的确切错误,但我在HP-UX aCC编译器中遇到了类似的错误。我在HP板上发布了有关它的信息,最终得到了HP的回复。 基本上他们的aCC版本3.xx(3.70,3.73,3.67等)搞砸了std::string结构。我们不得不迁移到编译器的 6.xx 版本。我们当时遇到的问题是,没有一个6.xx编译器可用于PA-RISC机器,只有Itanium。我相信 6.xx 编译器在 2007 年 9 月为 PA-RISC 发布。

出现问题的代码是:

#include <iostream>
#include <string>
class S : public std::string  // An extension of std::string
{
public:
  explicit S(const char* s)
    : std::string(s)
  {
  }
};
class N     // Wraps an int
{
public:
  explicit N(int n)
    : _n(n)
  {}
  operator S() const   // Converts to a string extension
  {
    return _n == 0 ? S("zero") : (_n == 1 ? S("one") : S("other"));
  }
private:
  int _n;
};
int main(int, char**)
{
  N n0 = N(0);
  N n1 = N(1);
  std::string zero = n0;
  std::cout << "zero = " << zero << std::endl;
  std::string one = n1;
  std::cout << "zero = " << zero
            << ", one = " << one << std::endl;
  return 0;
}

这是打印:
零 = 零
零 = 一,一 = 一

换句话说,从 n1 构造字符串 1 完全破坏了另一个字符串(字符串零)。

笔记:
要查看编译器的版本,请键入"aCC -V"
要查看机器的类型,请键入"uname -m"(9000/800 ==> PA-RISC,ia64 ==> Itanium)

这一定是一个错误。 std::string可以做引用计数的字符串作为它的实现,但是一旦它被改变,它应该"分叉"字符串。

这对我来说听起来确实是一个错误。 其他有权访问 HP/UX 的人可以重现这一点吗?

你是说这个程序在两行上显示相同的文本?

#include <stdio.h>
#include <string>
int main () 
{
    std::string s1 = "hello"; 
    std::string s2 = std::string(s1);   // note: std::string s2( s1); would reduce the number of copy ctor calls
    s2.append( ", world");
    printf( "%sn", s1.c_str());
    printf( "%sn", s2.c_str());
}

这两个字符串实际上是否发生了不同的变化,或者您是否在使用其他比较(例如 c_str()) 返回的地址)?

字符串的某些实现在进行复制时不会复制整个字符串,以加快长字符串的复制速度。如果尝试对任一字符串进行更改,则实现应复制字符串并进行适当的更改(理想情况下作为同一操作的一部分)。

这肯定是一个缺陷。 此示例是 C++ 标准的逐字记录:

string s1("abc");
string::iterator i = s1.begin();
string s2 = s1;
*i = ’a’;  // Must modify only s1